const express = require('express');
const router = express.Router();
const moment=require('moment');
router.get('/fun', (req, res) => {
    let name = req.query.name || '程宇';
    let age = req.query.age || 25;
    let content = req.query.content || 'JSONP测试';

    let data = {
        name: name,
        age: age,
        content: content
    };
    let callback = req.query.callback;
    let str = callback + '(' + JSON.stringify(data) + ')';
    res.type('text/javascript');
    res.send(str);

});


const wmf = require('../db/wmf');
//添加内容
router.post('/add', function (req, res) {
    let summary=req.body.detail.match(/[^><]+(?=<\/h2>)/img);
    let index=0;
    let detail=req.body.detail.replace(/<h2/g,function(str){
        index++;
        return `<h2 id="mifi${index}"`;
    })
    new wmf({
        time: moment().format('YYYY-MM-DD HH:mm'),
        detail:detail,
        title:req.body.title,
        tags:summary,
        num:0
    }).save().then(
        res.json({
            status: true,
            msg: '保存成功',
            data: req.body
        })
    );

});

//读取列表信息
router.get('/doclist',(req,res)=>{
    wmf.find({}).sort('-time').exec((err,data)=>{
        res.json({data})
    });
});
router.post('/edit', function (req, res) {
    let receive = req.body;
    if (!receive.id) {
        res.json({
            status: false,
            msg: '缺少参数ID'
        })
    } else {
        wmf.findOne({_id: receive.id}, (err, data) => {
            if (!err) {
                console.log(data)
                res.json({
                    status: true,
                    msg: '收到了请求'
                })
            } else {
                res.json({
                    status: false,
                    msg: err
                })
            }
        })
    }
});
//文章详情
router.get('/docdetail/:id', function (req, res) {
    
    let id=req.params.id;
    wmf.find({_id:id},(err,data)=>{
        if(!err)
        {
            data[0].num++;
            data[0].save();
            res.json(data[0])
        }
    });
});



router.get('/hot',async(req,res)=>{
    let limit=Number(req.query.limit)||5;
    const result=await wmf.find({}).sort('-num').limit(limit);
    res.json(result)
});

router.get('/addData',async(req,res)=>{
    let data=[];
    for(i=0;i<100;i++)
    {
        await new wmf({
            "tags" : [ 
                "标题1","标题2"
            ],
            "time" : moment().format('YYYY-MM-DD HH:mm'),
            "detail" : "<h2 id=\"mifi1\">一、标题1</h2>\n<h2 d=\"mifi2\">2.标题2</h2>\n<p>下面这一段可是代码啊</p>\n<pre><code>{{getdetail.next}}</code></pre>\n<h3>2.说不清楚</h3>\n<pre><code>{{getlist.prev}}</code></pre>",
            "title" : `伪造的数据${i}`,
            "num" : 0
        }).save()
    }


    res.json({msg:'伪造成功'})
});
module.exports = router;